import {resizeCustom} from "./loadDataSource.ts";
import { widgets as testWidgetNames } from '../../widgets.json';

const fetchWidget = (path: string) => fetch(path).then(res => res.text())
const localWidgetObject: Map<string, Promise<any>> = (import.meta as any).glob('/src/widget/**/index.tsx');

interface IWidgetRemote {
  id: string;
  version: string;
  name: string;
  type: string;
  renderProps: any;
  path: string; // "widgets/card.0.0.1.js"
  children: any[];
}

/**
 * 加载本地组件
 */
async function loadLocalWidgets () {
  const localWidgetMap = new Map()

  for (let [path, localWidget] of Object.entries(localWidgetObject)) {
    const widget = await localWidget();
    if (widget) {
      path = path.replace('/index.tsx', '')
      const widgetName = path.split('/').pop()
      const upperCaseName = widgetName!.toLocaleUpperCase();
      widget.settings.name = upperCaseName;
      resizeCustom(widget.settings)
      localWidgetMap.set(upperCaseName, widget)
      console.log('widgets: => ', upperCaseName, widget)
    }
  }

  console.log('localWidgetMap: => ', localWidgetMap)
  return localWidgetMap;
}

/**
 * 当前场景中用到的所有组件
 *
 * @param widgetData
 * @param cb
 */
async function loadRemoteWidgets(widgetData: IWidgetRemote[], cb: (arg: any) => void = () => {}) {
  const remoteWidgetMap: Map<string, any> = new Map()
  const localWidgetMap = await loadLocalWidgets()
  return Promise.all(
    widgetData
      .map(widget => fetchWidget(`/${widget.path}`)
        .then(componentText => {
          // 获取组件名称
          const nameLowerCase = widget.name.toLocaleLowerCase()
          // 执行组件
          eval(componentText)

          const remoteWidget = (window as any)[`$${nameLowerCase}`];
          remoteWidget.settings.name = widget.name;
          remoteWidgetMap.set(widget.name, remoteWidget);
          delete (window as any)[`$${nameLowerCase}`]
          return { name: nameLowerCase, componentText }
        }))
  ).then(() => {
    console.log('remoteWidgetMap', remoteWidgetMap)
    /**
     * 当前需要调试的本地组件
     * 如果与服务器组件同名，则优先使用本地调试。
     */
    remoteWidgetMap.forEach(widget => {
      const { name } = widget.settings
      if (testWidgetNames.includes(name)) {
        const localWidget = localWidgetMap.get(name)
        localWidget.settings.name = name;
        // console.log('localWidget', localWidget, name)
        resizeCustom(localWidget.settings)
        widget && remoteWidgetMap.set(name, localWidget)
      } else {
        const remoteWidget = remoteWidgetMap.get(name)
        // console.log('remoteWidget', remoteWidget, name)
        // resizeCustom(remoteWidget.settings)
        remoteWidgetMap.set(name, remoteWidget)
      }
    })
    cb(remoteWidgetMap)
  })
}